package org.csu.mypetstore.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.csu.mypetstore.config.AlipayConfig;
import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.LogService;
import org.csu.mypetstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private Order order;
    private boolean confirmed;
    @Autowired
    private List<Order> orderList;
    @Autowired
    private Account account;
    @Autowired
    private HttpSession session;

    @Autowired
    private Cart cart;

    @Autowired
    private CatalogService catalogService;

    @Autowired
    private LogService logService;

    @GetMapping("/listOrders")
    public String listOrders(HttpServletRequest req) {
        account = (Account) session.getAttribute("account");
        orderList = orderService.getOrdersByUsername(account.getUsername());
        session.setAttribute("orderList",orderList);
        if(account!=null)
        {
            HttpServletRequest httpRequest = req;
            String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                    + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());


            String logInfo = logService.logInfo(" ") + strBackUrl + "查看订单";
            logService.insertLogInfo(account.getUsername(), logInfo);
        }
        //跳到新
        return "order/ListOrders";
    }

    @GetMapping("/newOrderForm")
    public String newOrderForm(Model model) {
        account = (Account) session.getAttribute("account");
        cart = (Cart) session.getAttribute("cart");
        if (account == null) {
            model.addAttribute("msg", "You must sign on before attempting to check out.  Please sign on and try checking out again.");
            //跳到用户登录
            return "#";
        } else if (cart != null) {
            order.initOrder(account, cart);
            model.addAttribute("order", order);
            //跳到新订单
            return "order/dingdan";
        }
        else {
            model.addAttribute("message", "An order could not be created because a cart could not be found.");
            //不管
            return "#";
        }
    }

    @GetMapping("/comfirmToShowServlet")
    private String comfirmToShowServlet(int orderId)
    {
        order =orderService.getOrder(orderId);
        session.setAttribute("order",order);
        return "/order/ViewOrder";
    }

    @GetMapping("/viewOrder")
    public String viewOrder(Model model) {
            //跳到最后的成功界面
            return "order/ViewOrder";
    }

    @GetMapping("/comfirm")
    public String comfirmForm(Model model)
    {
        model.addAttribute("order",order);
        return "order/dingdan";
    }
    @PostMapping("/comfirm")
    public String comfirmSubmit(@ModelAttribute Order order)
    {
        account = (Account) session.getAttribute("account");
        Date orderDate = new Date();
        order.setOrderDate(orderDate);
        order.setUsername(account.getUsername());
        order.setCourier("UPS");
        order.setCardType("Visa");
        order.setLocale("CA");
        order.setStatus("not dilivered");
        cart = (Cart) session.getAttribute("cart");
        order.setTotalPrice(cart.getSubTotal());
        Iterator<CartItem> i = cart.getAllCartItems();
        while (i.hasNext()) {
            CartItem cartItem = (CartItem) i.next();
            order.addLineItem(cartItem);
        }
        List<LineItem> lineItems = order.getLineItems();
        Iterator<LineItem> it = lineItems.iterator ();
        while(it.hasNext())
        {
            LineItem lineItem = it.next();
            lineItem.calculateTotal();
        }
        session.setAttribute("order",order);
        order.setOrderId(orderService.getNextId("ordernum"));
//        orderService.insertOrder(order);
//        catalogService.removeAllByUserName(account.getUsername());
//        session.setAttribute("cart",null);
        return "order/ComfirmOrder";
    }

    public void clear(boolean shippingAddressRequired) {
        shippingAddressRequired = false;
        confirmed = false;
        orderList = null;
    }

    @RequestMapping("payment")
    public String payment(HttpServletRequest request , Model model, @ModelAttribute Order order, HttpServletResponse response){
        try {
            account = (Account) session.getAttribute("account");
            Order order2 = (Order) session.getAttribute("order");
            orderService.insertOrder(order2);
            catalogService.removeAllByUserName(account.getUsername());
            session.setAttribute("cart",null);
            //获得初始化的AlipayClient
            //AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                    "2021000117632552",
                    "MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQCdLHla+XR/a4iZTrMD3NYDkxzie019FplwSR4kXJBmRFVLjhp6KOpyS34k8G7TmF0AEgdvIC2rU6ae9cG8aSput7IFyzJNgGPp+KBr6CkylOu1c7GGNoefBIUw+cibM2n4N3b8XuRJCGVmVQN5d/pdzdd3ownwRY/trQOVi1ySvtjg2fVntupiTmuJLH54CThE2HNo2Hk4uKr3W/o+If8GoDdlAh/Me73qSZhHf3eR9LifDbXdtRmmq0a6aQ/2Ao6tgsT401SlU+AlkB1H+OPZlfb/TiAx7TBNLAw8IYPqYDuXEvEMtzFiG0sap8PlsHmAjQ0N95MD8zZ++RtfW4kpAgMBAAECggEBAIB+2pv4szh05pFHmO0Af2seu4+hdMFeV4VIEb9yeY9SMFV70MOsbbeRZoi2lDSjLO0g0DkWmp+l3OO6UXBCnjE0NvOrou1fmM+wtx5hCEVVILsQ4cKzE/96R5W5sDrKNsl6Numufn4Cwjt+J0AISYSlA5HIlhh8FmYee36oF7/TxJt0I13+6JEDEhEPYP5pR35UcVqcCVqk2KttJmSrnYIUVrbbnzjWNUMrBG0il9DKP4vefGcVgeIPSqvtnn/GwR9BSKzmLvfRO5Vt8mQqjdwSSjQUS3V434lQ3LN7zHcgPf+5fn1Hi035GaPAePBAQ7qL0qrTg8Hw+HKrcKOJ2m0CgYEA1JVKO2erciz8dxXolpDk9suWWhzdzJVqSsbYZpWf0Qkno1aHBtLUVFpcCqN9dlUavFLFL4XFeYl0mKrtV6Vl4VGF8MTZ5qyA5QYvKduqObEvKG5EWW7zppYT86p7P/2xo4yqERvXo/Glcd/c9382dVwX9cn6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GzhAq+a+TWjIm4uiVq1Elq/CA1My43snCpVkeneTVYzSaDioIDQIDAQAB",
                    "RSA2");
            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            String s=String.valueOf(1123);
            System.out.println(request.getParameter("orderId")+"***********************************");
            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no =request.getParameter("orderId");
            //付款金额，必填
            String total_amount =request.getParameter("totalprice");
            //订单名称，必填
            String subject = request.getParameter("totalprice")+"'s Order";

            //商品描述，可空
            String body = "";

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    +"\"body\":\""+body+"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
            //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
            //		+ "\"total_amount\":\""+ total_amount +"\","
            //		+ "\"subject\":\""+ subject +"\","
            //		+ "\"body\":\""+ body +"\","
            //		+ "\"timeout_express\":\"10m\","
            //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

            //请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();

            //输出
            System.out.println(result);
            model.addAttribute("result",result);
            response.getWriter().write(result);
            return "order/payment";
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
